package com.tnl.app.controller;

import java.io.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.tnl.app.config.GlobalConfig;
import com.tnl.app.dao.*;
import com.tnl.app.entity.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dyplsapi.model.v20170525.BindAxbResponse;
import com.aliyuncs.dyplsapi.model.v20170525.UnbindSubscriptionResponse;
import com.aliyuncs.exceptions.ClientException;
import com.biz.hunter.db.entity.UserInfo;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.wxaapp.api.WxaTemplate;
import com.tnl.app.service.IEmployeeService;
import com.tnl.app.service.impl.SMSService;
import com.tnl.base.web.JsonController;
import com.tnl.utils.DateUtil;
import com.tnl.utils.RadomUtils;
import com.tnl.utils.SecretAXB;
import com.tnl.utils.WXBizDataCrypt;
import com.tnl.utils.WxaTemplateUtil;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/user")
public class UserController extends JsonController {
	
	public static final String QNACCESS_KEY = "fc3vAVzCctz8YXwyyr6W3TBAiZKMHQknqY4ObUKL";
	 public static final String QNSECRET_KEY = "f_xZjBzq258akREeoZJeqbRDhISZV6nu8Tu4_mw1";
	 
    @Autowired
    private EmployeeDAO employeeDAO;
    @Autowired
    private PersonDAO personDAO;
    @Autowired
    private CompanyDAO companyDAO;
    @Autowired
    private JobTitleDAO jobTitleDAO;
    @Autowired
    private CityDAO cityDAO;
    @Autowired
    private DomainDAO domainDAO;
    @Autowired
    private OpinionDAO opinionDAO;
    @Autowired
    private WxAppUserDAO wxAppUserDAO;
    @Autowired
    private OrderDAO orderDAO;
    @Autowired
    private HunterDAO hunterDAO;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private SMSService smsService;

    @Autowired
    private TbFileDAO tbFileDAO;

    @Autowired
    private RecommendRecordDAO recommendRecordDAO;

    @Autowired
    private RecommendDAO recommendDAO;

    @Autowired
    private JobDAO jobDAO;
    @Autowired
    private UserInfoDAO userInfoDAO;

    private static final Logger logger = LoggerFactory
            .getLogger(UserController.class);

    /**
     * 直通车
     *
     * @param response
     */
    @RequestMapping(value = "getResume")
    public void getResume(HttpServletResponse response, String openid) {
        Employee emp = employeeDAO.getByOpenId(openid);
        this.successJson(emp, "个人资料", response);
    }

    /**
     * 保存个人基本信息资料
     *
     * @param response
     */
    @RequestMapping(value = "saveResumeBase")
    public void saveResumeBase(HttpServletResponse response, String openid,
                               String name, Integer workage, Integer cityindex, String phone,
                               String email, String mark, Integer contactindex) {
        int flag = 0;
        WxAppUser user = wxAppUserDAO.getByOpenId(openid);
        Person person = personDAO.getByPhone(user.getMobile());
        if (person != null) {
            person.setName(name);
            person.setWorkage(workage);
            person.setCityId(cityindex + 1);
            person.setPhone(phone);// 多余
            person.setEmail(email);
            person.setComment(mark);
            if (contactindex == 2) {
                person.setIntentTime(6);
            } else if (contactindex == 3) {
                person.setIntentTime(12);
            }
            flag = employeeService.updateBaseProfile(person);
        } else {
            person = new Person();
            person.setOpenid(openid);
            person.setName(name);
            person.setWorkage(workage);
            person.setCityId(cityindex + 1);
            person.setPhone(phone);// 多余
            person.setEmail(email);
            person.setComment(mark);
            if (contactindex == 0) {
                person.setIntentTime(0);
            } else if (contactindex == 1) {
                person.setIntentTime(1);
            } else if (contactindex == 2) {
                person.setIntentTime(6);
            } else if (contactindex == 3) {
                person.setIntentTime(12);
            }
            flag = employeeService.SavePersonBaseProfile(person);
        }
        this.successJson(flag, "保存个人资料", response);
    }

    /**
     * 选择行业领域
     *
     * @param response
     * @param domainId
     * @param openid
     * @param majorDomainId1
     * @param majorDomainId2
     * @param majorDomainId3
     */
    @RequestMapping(value = "saveResumeDomain")
    public void saveResumeDomain(HttpServletResponse response,
                                 Integer domainId, String openid, Integer majorDomainId1,
                                 Integer majorDomainId2, Integer majorDomainId3) {
        int flag = 0;
        Integer newdomainId = domainId;
        WxAppUser user = wxAppUserDAO.getByOpenId(openid);
        Employee emp = employeeDAO.getEmpByPhone(user.getMobile());
        Person person = personDAO.getByPhone(user.getMobile());
        if (person != null && emp != null) {
            person.setDomainId(domainId);
            Domain dm = domainDAO.getById(domainId);
            person.setDomainName(dm.getName());
            emp.setDomainId(domainId);
            emp.setDomainName(dm.getName());
            emp.setMajorDomainId1(majorDomainId1);
            emp.setMajorDomainId2(majorDomainId2);
            emp.setMajorDomainId3(majorDomainId3);
            employeeService.saveResumeDomain(emp, person);
        } else {
            emp = new Employee();
            person.setDomainId(newdomainId);
            Domain dm = domainDAO.getById(newdomainId);
            person.setDomainName(dm.getName());
            person.setOpenid(openid);
            emp.setPersonId(person.getId());
            emp.setDomainId(newdomainId);
            emp.setDomainName(dm.getName());
            emp.setMajorDomainId1(majorDomainId1);
            emp.setMajorDomainId2(majorDomainId2);
            emp.setMajorDomainId3(majorDomainId3);
            emp.setOpenid(openid);
            employeeService.saveResumeCreateDomain(emp, person);
            this.errorJson(flag, "update fail", response);
        }
        this.successJson(flag, "update success", response);
    }

    /**
     * 现任职位
     *
     * @param response
     * @param companyname
     * @param posi
     * @param bestdomain
     * @param openid
     */
    @RequestMapping(value = "saveResumeNowPosi")
    public void saveResumeNowPosi(HttpServletResponse response,
                                  String companyname, Integer posi, String bestdomain, String openid) {
        int flag = 0;
        WxAppUser user = wxAppUserDAO.getByOpenId(openid);
        Person person = personDAO.getByPhone(user.getMobile());
        if (person != null) {
            // 如果该公司不存在数据库里，那么companyid为0，表明该公司需要归一化
            Company company = companyDAO.getByName(companyname);
            if (company == null) {
                person.setCompanyId(0);//
            } else {
                person.setCompanyId(company.getId());
            }
            person.setCompanyName(companyname);
            person.setRoleId(posi);
            JobTitle jd = this.jobTitleDAO.getById(posi);
            if (jd != null) {
                logger.debug("add job info job name is " + jd.getName());
                person.setRoleName(jd.getName());
            }
            person.setBestdomain(bestdomain);
            flag = employeeService.saveResumeNowPosi(person);
        } else {
            this.errorJson(flag, "update fail", response);
        }
        this.successJson(flag, "update success", response);
    }

    /**
     * 期望
     *
     * @param response
     * @param expectcompanyId1
     * @param expectcompanyId2
     * @param expectcompanyId3
     * @param expectJob
     * @param openid
     */
    @RequestMapping(value = "saveResumeDreamPosi")
    public void saveResumeDreamPosi(HttpServletResponse response,
                                    Integer expectcompanyId1, Integer expectcompanyId2,
                                    Integer expectcompanyId3, Integer expectJob, String openid) {
        int flag = 0;
        WxAppUser user = wxAppUserDAO.getByOpenId(openid);
        Employee emp = employeeDAO.getEmpByPhone(user.getMobile());
        if (emp != null) {
            // 如果该公司不存在数据库里，那么companyid为0，表明该公司需要归一化
            Company company = companyDAO.getById(expectcompanyId1);
            if (company == null) {
                emp.setExpectCompany1(0);
            } else {
                emp.setExpectCompany1(company.getId());
                emp.setExpectCompanyName1(company.getName());
            }

            Company company2 = companyDAO.getById(expectcompanyId2);
            if (company2 == null) {
                emp.setExpectCompany2(0);
            } else {
                emp.setExpectCompany2(company.getId());
                emp.setExpectCompanyName2(company2.getName());
            }

            Company company3 = companyDAO.getById(expectcompanyId3);
            if (company3 == null) {
                emp.setExpectCompany3(0);
            } else {
                emp.setExpectCompany3(company.getId());
                emp.setExpectCompanyName3(company3.getName());
            }
            emp.setExpectJob(expectJob);
            JobTitle jd = this.jobTitleDAO.getById(expectJob);
            if (jd != null) {
                logger.debug("add job info job name is " + jd.getName());
                emp.setExpectJobName(jd.getName());
            }

            flag = employeeService.saveResumeDreamPosi(emp);
        } else {
            this.errorJson(flag, "update fail", response);
        }
        this.successJson(flag, "update success", response);
    }

    @RequestMapping(value = "getCompanyByDomain")
    public void getCompanyByDomain(HttpServletResponse response,
                                   Integer domainId, Integer majorDomainId1) {
        List<Company> company = companyDAO.getCompanyByDomain(domainId, majorDomainId1);
        this.successJson(company, "根据领域选择公司", response);
    }


    @RequestMapping(value = "getCompanyByEmpDomain")
    public void getCompanyByEmpDomain(HttpServletResponse response,
                                      String openid) {
        Employee emp = employeeDAO.getByOpenId(openid);
        List<Company> company = companyDAO.getCompanyByDomain(emp.getDomainId(), emp.getMajorDomainId1());
        this.successJson(company, "根据领域选择公司", response);
    }

    @RequestMapping(value = "do_register")
    public void genSecurityCode(HttpServletResponse response, String phone,
                                String openid) {
        Employee emp = employeeService.getEmpByPhone(phone, openid);
        String secureCode = null;
        if (emp != null) {
            // get expiredDate
            secureCode = emp.getSecureCode();
        } else {
            RadomUtils radom = new RadomUtils();
            // gen code
            secureCode = radom.getRadom(4);
            // save code

            emp = new Employee();
            /*
             * if (user != null) { emp.setName(user.getNickname());//根据微信获取昵称 }
             */
            emp.setOpenid(openid);
            emp.setPhone(phone);
            emp.setActive(1);
            emp.setSecureCode(secureCode);// 重复的
            emp.setState(Person.State.generated.toString());

            java.util.Date timeDate = new Date();// util类型
            long time = timeDate.getTime();
            java.sql.Timestamp dateTime = new java.sql.Timestamp(time);// Timestamp类型,timeDate.getTime()返回一个long型

            emp.setExpiredTime(dateTime);
            employeeService.saveSecureCode(emp);
        }
        try {
            smsService.sendSMS(phone, secureCode);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.successJson(secureCode, "验证注册验证码", response);
    }

    /**
     * 所有公司
     *
     * @param response
     */
    @RequestMapping(value = "getCompany")
    public void getCompany(HttpServletResponse response) {
        List<Company> companies = companyDAO.getALL();
        this.successJson(companies, "所有公司", response);

    }

    @RequestMapping(value = "getFunction")
    public void getjobfunction(HttpServletResponse response) {
        List<JobTitle> list = jobTitleDAO.getPostTypes();
        if (list != null) {
            for (JobTitle jd : list) {
                int postype = jd.getPostype();
                String postypeStr = null;
                switch (postype) {
                    case 1:
                        postypeStr = "高级管理";
                        break;
                    case 2:
                        postypeStr = "法务";
                        break;
                    case 3:
                        postypeStr = "人力资源";
                        break;
                    case 4:
                        postypeStr = "咨询/项目";
                        break;
                    case 5:
                        postypeStr = "财务";
                        break;
                    case 6:
                        postypeStr = "信息技术";
                        break;
                    case 7:
                        postypeStr = "业务拓展及招投标";
                        break;
                    case 8:
                        postypeStr = "市场";
                        break;
                    case 9:
                        postypeStr = "销售";
                        break;
                    case 10:
                        postypeStr = "客服中心";
                        break;
                    case 11:
                        postypeStr = "研发";
                        break;
                    case 12:
                        postypeStr = "供给/物流";
                        break;
                    case 13:
                        postypeStr = "质量监督";
                        break;
                    case 14:
                        postypeStr = "医学事务";
                        break;
                    case 15:
                        postypeStr = "临床";
                        break;
                    case 16:
                        postypeStr = "生物技术研发";
                        break;
                    case 17:
                        postypeStr = "药剂";
                        break;
                    case 18:
                        postypeStr = "工厂生产";
                        break;
                    case 19:
                        postypeStr = "行政";
                        break;
                }
                jd.setPostypeStr(postypeStr);
            }
        }
        this.successJson(list, "所属职能", response);
    }

    @RequestMapping(value = "getJobByTypes")
    public void getJobByTypes(HttpServletResponse response, Integer postype) {
        List<JobTitle> list = jobTitleDAO.getJobByTypes(postype);
        if (list != null) {
            for (JobTitle jd : list) {
                int postype1 = jd.getPostype();
                String postypeStr = null;
                switch (postype1) {
                    case 1:
                        postypeStr = "高级管理";
                        break;
                    case 2:
                        postypeStr = "法务";
                        break;
                    case 3:
                        postypeStr = "人力资源";
                        break;
                    case 4:
                        postypeStr = "咨询/项目";
                        break;
                    case 5:
                        postypeStr = "财务";
                        break;
                    case 6:
                        postypeStr = "信息技术";
                        break;
                    case 7:
                        postypeStr = "业务拓展及招投标";
                        break;
                    case 8:
                        postypeStr = "市场";
                        break;
                    case 9:
                        postypeStr = "销售";
                        break;
                    case 10:
                        postypeStr = "客服中心";
                        break;
                    case 11:
                        postypeStr = "研发";
                        break;
                    case 12:
                        postypeStr = "供给/物流";
                        break;
                    case 13:
                        postypeStr = "质量监督";
                        break;
                    case 14:
                        postypeStr = "医学事务";
                        break;
                    case 15:
                        postypeStr = "临床";
                        break;
                    case 16:
                        postypeStr = "生物技术研发";
                        break;
                    case 17:
                        postypeStr = "药剂";
                        break;
                    case 18:
                        postypeStr = "工厂生产";
                        break;
                    case 19:
                        postypeStr = "行政";
                        break;
                }
                jd.setPostypeStr(postypeStr);
            }
        }
        this.successJson(list, "所属职能", response);
    }

    /**
     * 所有职位
     *
     * @param response
     */
    @RequestMapping(value = "getjobtitle")
    public void getjobtitle(HttpServletResponse response) {
        List<JobTitle> list = jobTitleDAO.getALL();
        if (list != null) {
            for (JobTitle jd : list) {
                int postype = jd.getPostype();
                String postypeStr = null;
                switch (postype) {
                    case 1:
                        postypeStr = "高级管理";
                        break;
                    case 2:
                        postypeStr = "法务";
                        break;
                    case 3:
                        postypeStr = "人力资源";
                        break;
                    case 4:
                        postypeStr = "咨询/项目";
                        break;
                    case 5:
                        postypeStr = "财务";
                        break;
                    case 6:
                        postypeStr = "信息技术";
                        break;
                    case 7:
                        postypeStr = "业务拓展及招投标";
                        break;
                    case 8:
                        postypeStr = "市场";
                        break;
                    case 9:
                        postypeStr = "销售";
                        break;
                    case 10:
                        postypeStr = "客服中心";
                        break;
                    case 11:
                        postypeStr = "研发";
                        break;
                    case 12:
                        postypeStr = "供给/物流";
                        break;
                    case 13:
                        postypeStr = "质量监督";
                        break;
                    case 14:
                        postypeStr = "医学事务";
                        break;
                    case 15:
                        postypeStr = "临床";
                        break;
                    case 16:
                        postypeStr = "生物技术研发";
                        break;
                    case 17:
                        postypeStr = "药剂";
                        break;
                    case 18:
                        postypeStr = "工厂生产";
                        break;
                    case 19:
                        postypeStr = "行政";
                        break;
                }
                jd.setPostypeStr(postypeStr);
            }
        }
        this.successJson(list, "所有职位", response);
    }

    /**
     * 所有城市
     *
     * @param response
     */
    @RequestMapping(value = "getcity")
    public void getcity(HttpServletResponse response) {
        List<City> companies = cityDAO.getALL();
        this.successJson(companies, "所有城市", response);
    }

    /**
     * 所有领域
     *
     * @param response
     */
    @RequestMapping(value = "getdomain")
    public void getdomain(HttpServletResponse response) {
        List<Domain> domain = domainDAO.getBaseDomain();
        this.successJson(domain, "所有领域", response);
    }

    // 医药
    @RequestMapping(value = "getdrugdomain")
    public void getdrugdomain(HttpServletResponse response) {
        JSONObject json = new JSONObject();
        json.put("drug", domainDAO.getAllDrugDomain());
        this.successJson(json, "所有领域", response);
    }

    @RequestMapping(value = "getSubDomain")
    public void getChildDomain(Integer domainId, HttpServletResponse response) {
        List<Domain> domain = domainDAO.getAllSubDomain(domainId);
        this.successJson(domain, "所有领域", response);
    }

    // 医疗
    @RequestMapping(value = "getmeddomain")
    public void getmeddomain(HttpServletResponse response) {
        JSONObject json = new JSONObject();
        json.put("drug", domainDAO.getAllMedicalDomain());
        this.successJson(json, "所有领域", response);
    }

    /**
     * 预约提醒（由最初开始设计opinion修改提醒）
     *
     * @param response
     * @param title
     * @param desc
     * @param openid
     */
    @RequestMapping(value = "addOpinion")
    public void addOpinion(HttpServletResponse response, String formId, String hunterId, String title,
                           String desc, String openid) {
        Hunter hunter = hunterDAO.getById(Integer.parseInt(hunterId));
        Opinion opinion = new Opinion();
        opinion.setHunterId(Integer.parseInt(hunterId));
        opinion.setTitle(title);
        opinion.setDesciption(desc);
        opinion.setOpenid(openid);
        int flag = opinionDAO.save(opinion);
        if (flag > 1) {
            String tempjson = new WxaTemplate()
                    .setTouser(openid)
                    .setTemplate_id("Ng_4IN-cZqippsDWhO6YDgDqQlsRKSDvWxYMiFpRfGQ")
                    .setForm_id(formId)
                    .setPage("pages/index/index")
                    .add("keyword1", title, "#000000")
                    .add("keyword2", desc, "#000000")
                    .add("keyword3", "感谢您的填写，已通知咨询师开放您需预约时段，请耐心等待！过程中如遇到问题，请添加客服微信：ElenaYu807 询问。", "#F47e2d")
                    .build();
            System.out.println(tempjson);
            boolean res = WxaTemplateUtil.sendTemplateMsg(tempjson);
            //push hunter
            try {
                smsService.sendOrdRemindSMS(hunter.getPhone(), desc);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String tempjsonhunter = TemplateData.New()
                    .setTouser(hunter.getOpenid())
                    .setTemplate_id("jgp1jc6kfNGSJ-S5zp1jLTFyUDkB9tKLxKu6vmS1h-g")
                    .setUrl("https://www.headoffer.com/hrplus")
                    .add("first", "您好，新的用户想要预约您的咨询项目，开放相应预约时段。", "#274084")
                    .add("keyword1", "用户：" + title.substring(0, 6) + "****" + "预约咨询", "#000000")
                    .add("keyword2", desc, "#F47e2d")
                    .add("keyword3", DateUtil.currentTime(), "#000000")
                    .add("remark", "温馨提示：开放预约时段前往顾问后台Open时间即可，过程中如遇到问题，请添加客服微信：ElenaYu807 询问。", "#274084")
                    .build();
            System.out.println(tempjsonhunter);
            ApiResult reshunter = TemplateMsgApi.send(tempjsonhunter);
            System.out.println("模板消息发送结果：" + reshunter);
            System.out.println("模板消息发送结果：" + res);
            this.successJson(flag, "新增成功", response);
        } else {
            this.errorJson(flag, "Opinion add fail", response);
        }

    }


    /**
     * 我想知道
     */
    @RequestMapping(value = "addPosiOpinion")
    public void addPosiOpinion(HttpServletResponse response, String title, String desc, String openid) {
        Opinion opinion = new Opinion();
        opinion.setTitle(title);
        opinion.setDesciption(desc);
        opinion.setOpenid(openid);
        int flag = opinionDAO.save(opinion);
        if (flag > 1) {
            this.successJson(flag, "我想知道新增成功", response);
        } else {
            this.errorJson(flag, "Opinion add fail", response);
        }

    }

    /**
     * 是否已预约过一次
     *
     * @param response
     * @param openid
     */
    @RequestMapping(value = "isOpinionFirst")
    public void isOpinionFirst(HttpServletResponse response, String openid) {
        Opinion opinion = opinionDAO.getOptionByCreatedate(openid);
        this.successJson(opinion != null ? opinion.getId() : 0, "是否已预约过了", response);
    }


    /**
     * 用微信自动获取用户的手机号码组件
     *
     * @param response
     * @param openid   phoneNumber:用户绑定的手机号（国外手机号会有区号）
     *                 purePhoneNumber:没有区号的手机号
     *                 countryCode:区号
     */
    @RequestMapping(value = "getPhoneNumber")
    public void getPhoneNumber(HttpServletResponse response, String openid, String iv,
                               String encrydata, String sessionKey) {
        String deString = null;
        try {
            deString = WXBizDataCrypt.getInstance().decrypt(encrydata, sessionKey, iv, "utf-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(deString);
        JSONObject jsonObject = JSONObject.parseObject(deString);
        String countryCode = jsonObject.getString("countryCode");
        String phoneNumber = jsonObject.getString("phoneNumber");
        String purePhoneNumber = jsonObject.getString("purePhoneNumber");
        int flag = wxAppUserDAO.updateMobile(phoneNumber, purePhoneNumber, countryCode, openid);
        logger.info("手机号绑定：" + flag);
        this.successJson(phoneNumber, "手机号码绑定成功", response);

    }

    /**
     * 虚拟号码拨打
     * orderTime.substring(orderTime.length()-5,orderTime.length())
     */
    @RequestMapping(value = "callPhone")
    public void callPhone(HttpServletResponse response, String openid, String orderId) {
        Order order = orderDAO.getById(Integer.parseInt(orderId));
        Employee emp = employeeDAO.getByEmpId(order.getEmployeeId());
        Hunter hunter = hunterDAO.getById(order.getHunterId());
        try {
            String orderTime = order.getOrderTime();
            //AXB绑定
            logger.info("失效时间==" + orderTime.subSequence(0, 10) + " " + orderTime.substring(orderTime.length() - 5, orderTime.length()) + ":00");
            BindAxbResponse axbResponse = SecretAXB.bindAxb(emp.getPhone(), hunter.getPhone(), orderTime.subSequence(0, 10) + " " + "00:00:00");
            logger.info("AXB绑定接口返回的结果----------------");
            logger.info("Code=" + axbResponse.getCode());
            logger.info("Message=" + axbResponse.getMessage());
            logger.info("RequestId=" + axbResponse.getRequestId());
            String axbSubsId = axbResponse.getSecretBindDTO() == null ? null : axbResponse.getSecretBindDTO().getSubsId();
            String axbSecretNo = axbResponse.getSecretBindDTO() == null ? null : axbResponse.getSecretBindDTO().getSecretNo();
            logger.info("subsId=" + axbSubsId);
            logger.info("secretNo=" + axbSecretNo);

            //预留一分钟给您做拨打测试
            Thread.sleep(60000L);

            if (axbResponse.getCode() != null && axbResponse.getCode().equals("OK")) {
                UnbindSubscriptionResponse unbind = SecretAXB.unbind(axbSubsId, axbSecretNo);
                logger.info("解绑接口返回数据AXB----------------");
                logger.info("Code=" + unbind.getCode());
                logger.info("Message=" + unbind.getMessage());
                logger.info("RequestId=" + unbind.getRequestId());
            }


            this.successJson(axbResponse.getCode(), "返回成功", response);
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @RequestMapping(value = "getInterviewRecord")
    public void getRecommendRecord(String unionid, String openId, HttpServletResponse response) {
        Employee emp = employeeService.getEmpByUnionid(unionid);
        Person person = employeeService.getById(emp.getPersonId());
        List<Recommend> recommendationList = recommendDAO.getByPersonAndStatus(person.getId(), 0);
        this.successJson(recommendationList, "职位沟通邀请", response);
    }

    @RequestMapping(value = "updateRecommendStatus")
    public void updateRecommendStatus(String unionid, String openId, Integer status, Integer id, HttpServletResponse response) {
        Employee emp = employeeService.getEmpByUnionid(unionid);
//        Person person = employeeService.getById(emp.getPersonId());
        Recommendation recommendation = new Recommendation();
        recommendation.setId(id);
        recommendation.setStatus(status);
        int row = recommendDAO.update(recommendation);
        RecommendRecord record = new RecommendRecord();
        record.setRecommendId(id);
        record.setStatus(status.intValue());
        switch (status.intValue()) {
            case 7:
                record.setRemark("同意职位沟通");
                break;
            case 8:
                record.setRemark("不同意职位沟通");
        }
        Long saveres = recommendRecordDAO.save(record);
        logger.info("insert recommendrecord return value=" + saveres);


        Recommendation recommend = this.recommendDAO.getById(id + "");
        JobDesc jobdesc = jobDAO.getById(recommend.getJobId());
        Company company2 = this.companyDAO.getById(jobdesc.getCompanyId());
        Person person = personDAO.getById(recommend.getPersonId());
        Employer employer = recommendDAO.getEmployerById(Integer.valueOf(jobdesc.getCreatedby()));
        if (status.intValue() == 7) {
            TemplateData template = TemplateData.New()
                    .setTouser(person.getOpenid())
                    .setTemplate_id("9IONF-cOb1FoehRIbv7ImA-g7apDRn6wFEOmiXE2rRo")
                    .setUrl("")
                    .add("first", "您好,您已接受了「" + company2.getName() + "」的HR面试前职位沟通邀请。", "#274084")
                    .add("keyword1", jobdesc.getName(), "#000000")
                    .add("keyword2", DateUtil.getDateTimeStr(new Date()), "#F47e2d")
                    .add("remark", "随后HR电话联系您，敬请留意！", "#000000");
            String tempjson = JSONObject.toJSONString(template);
            System.out.println(tempjson);
            ApiResult result = TemplateMsgApi.send(tempjson);
            logger.info("候选人端同意职位沟通确认，推送消息结果=" + result);


            String tempjsonhunters = com.jfinal.weixin.sdk.api.TemplateData.New().
                    setTouser(employer.getOpenid()).setTemplate_id("QHFnyrp6TKhqOtQmRtg-JN9mbyj6wcOYyHJaS-SsZt4")
                    .setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/hr/toInterview.do?recommendid=" + recommend.getId())
                    .add("first", "亲爱的HR您好,候选人" + person.getName() + "已接受了您的面试前职位沟通邀请。", "#274084")
                    .add("keyword1", jobdesc.getName(), "#000000")
                    .add("keyword2", DateUtil.getDateTimeStr(new Date()), "#F47e2d").add("remark", "您可点击详情查看对方联系方式进行沟通啦。", "#000000").build();
            System.out.println(tempjsonhunters);
            ApiResult resulthunters = WxaTemplateUtil.send(tempjsonhunters);
            logger.info("推送会猎端职位沟通确认消息结果=" + resulthunters);
        } else if (status.intValue() == 8) {
            String tempjson = TemplateData.New().setTouser(person.getOpenid())
                    .setTemplate_id("uFhqauO7S5lqI_Eta8nFiVO0WKxstaVQFla4tG3MWVI")
                    .setUrl("").add("first", "您好,您已拒绝了「" + company2.getName() + "」的HR面试前职位沟通邀请。", "#274084")
                    .add("keyword1", jobdesc.getName(), "#000000")
                    .add("keyword2", DateUtil.getDateTimeStr(new Date()), "#F47e2d")
                    .add("remark", "您可点击查看详情查看更多机会~", "#000000").build();
            System.out.println(tempjson);
            ApiResult result = TemplateMsgApi.send(tempjson);
            logger.info("候选人端不同意职位沟通确认，推送消息结果=" + result);


            String tempjsonhunters = com.jfinal.weixin.sdk.api.TemplateData.New().setTouser(employer.getOpenid()).setTemplate_id("D91ZzjK2_V5b7Anf_kWRHRbBhxHUOGlFkuEXSV5OiAQ").setUrl("https://www.tiaonali.com/tnl-hunter/wechat/hunter/hr/jobcandidatelist.page").add("first", "亲爱的HR您好,候选人" + person.getName() + "拒绝您本次的面试前的职位沟通邀请", "#274084").add("keyword1", jobdesc.getName(), "#000000").add("keyword2", com.biz.wechat.util.DateUtil.getDateTimeStr(new Date()), "#F47e2d").add("remark", "您可点击查看详情查看更多候选人的简历~", "#000000").build();
            System.out.println(tempjsonhunters);
            ApiResult resulthunters = WxaTemplateUtil.send(tempjsonhunters);
            logger.info("会猎端不同意职位沟通确认，推送消息结果=" + resulthunters);
        }

    }

    @RequestMapping(value = "getResumeList")
    public void getResumeList(String unionid, String openId, HttpServletResponse response) {
        System.out.println("-----" + unionid + " ======" + openId);
        Employee emp = employeeService.getEmpByUnionid(unionid);
        Person person = employeeService.getById(emp.getPersonId());
        List<TbFile> tbFile = tbFileDAO.getDocByPersonId(person.getId());
        this.successJson(tbFile, "个人简历", response);
    }


    @RequestMapping(value = "deleResume")
    public void deleResume(String unionid, Integer id, HttpServletResponse response) {
        Employee emp = employeeService.getEmpByUnionid(unionid);
        Person person = employeeService.getById(emp.getPersonId());
        tbFileDAO.del(id, person.getId());
        this.successJson("success", "删除成功", response);
    }


    @RequestMapping(value = "uploadResume")
    @ResponseBody
    public Map<String, Object> upload(HttpServletRequest servletRequest,
    		MultipartFile file,
    		@RequestParam String unionid,
    		@RequestParam String fileName) throws Exception {
    	System.out.println(file.getName());
        System.out.println("unionid:"+unionid+" fileName:"+fileName);
    	Employee emp = employeeService.getEmpByUnionid(unionid);
        Person person = employeeService.getById(emp.getPersonId());
        Map<String, Object> map = new HashMap<>();
        String documentId=null;
        if(file!=null&&file.getSize()>0){
			String path = "/usr/share/tomcat8/upload/";
//			String fileName = file.getOriginalFilename();
		    String suffix=fileName.substring(fileName.lastIndexOf(".")+1);
			FileOutputStream fos = null;
			documentId="doc-"+DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")+String.format("%04d",new Random().nextInt(9999));
			String newFileName = documentId+"."+suffix;// 避免冲突
			String filePath=path+ newFileName;
			
			try {
				fos = FileUtils.openOutputStream(new File(filePath));
				IOUtils.copy(file.getInputStream(), fos);

			//调用七牛云api，暂不封装 FileUtils.uploadFile(filePath, newFileName, "headoffer", Zone.zone0());
			
				Configuration cfg = new Configuration(Zone.zone0());
				UploadManager uploadManager = new UploadManager(cfg);
				Auth auth = Auth.create(QNACCESS_KEY, QNSECRET_KEY);
				String upToken = auth.uploadToken("headoffer");
				Response res = uploadManager.put(filePath, fileName, upToken);
				// 解析上传成功的结果
				DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
				
				TbFile tbFile=new TbFile();
				tbFile.setDocId(documentId);
				tbFile.setJobId(0);
				tbFile.setPersonId(person.getId());
				tbFile.setStudentId("");
				tbFile.setOriginal_name(fileName);
				tbFile.setNew_name(newFileName);
				tbFile.setFile_type(suffix);
				tbFile.setFile_path(filePath);
				tbFile.setRelative_path("https://tiaonali.com/"+newFileName);
				tbFile.setCreat_time(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
				tbFile.setUpdate_time(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
				tbFileDAO.saveNEW(tbFile);
				
			} catch(Exception e) {
				map.put("statusCode",500);
				e.printStackTrace();
			} finally {
				fos.close();
			}
			map.put("statusCode",200);
		 }
        map.put("statusCode",500);
        map.put("msg","file is empty");
        return map;
    }


    public static String uploadFile(String filePath, String fileName, String bucketName, int zoneName) {
        try {
            Zone zone = Zone.zoneNa0();
            if (zoneName == 0) {// 华南
                zone = Zone.zone0();
            }
            if (zoneName == 1) {// 华北
                zone = Zone.zone0();
            }
            if (zoneName == 2) { // 华东
                zone = Zone.zone0();
            }

            Configuration cfg = new Configuration(zone);
            UploadManager uploadManager = new UploadManager(cfg);
            Response response = uploadManager.put(filePath, fileName, token(bucketName));
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.info(fileName + "----文件上传失败----" + r.toString());
            try {
                System.err.println(r.bodyString());
                logger.info(fileName + "----文件上传失败----" + r.toString());
            } catch (QiniuException ex2) {
                // ignore
            }
            return null;
        }
    }


    /**
     * 默认存储空间
     *
     * @param bucketName
     * @return
     */
    public static String token(String bucketName) {
        Auth auth = Auth.create(GlobalConfig.QNACCESS_KEY, GlobalConfig.QNSECRET_KEY);
        String upToken = auth.uploadToken(bucketName);
        return upToken;
    }
    
    @RequestMapping(value = "checkPhone")
    @ResponseBody
    public Boolean checkPhone(String phone) {
    	Employee emp = employeeService.getEmpByPhone(phone);
    	return emp == null ? true : false;
    }

    @RequestMapping(value = "getByUnionid")
    @ResponseBody
    public EmployeePerson getByUnionid(String unionid,HttpServletResponse response) {
    	if (unionid == null || unionid == "") {
    		return null;
    	}
    	EmployeePerson emp = employeeService.getEmpPersonByUnionid(unionid);
    	return emp;
    }
    
    /**
     * 新版注册，openid存unionid
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public EmployeePerson save(EmployeePerson emp) {
    	System.out.println("=========================");
    	System.out.println("openId:"+emp.getOpenid());
    	System.out.println("domainid:"+emp.getMajorDomainId2());
    	System.out.println("domainid:"+emp.getMajorDomainId2());
//    	UserInfo userinfo =userInfoDAO.getByUnionid(emp.getOpenid());
//    	emp.setOpenid(userinfo.getOpenid());
//    	System.out.println("unionid:"+emp.getOpenid());
    	EmployeePerson emperson = employeeService.save(emp);
    	return emperson;
    }
}
